<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['model:base:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['model:base:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['model:base:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['model:base:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe v-loading="loading" :data="baseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" width="60" prop="modelId" />
      <el-table-column label="模型名称" align="left" prop="modelName" :show-overflow-tooltip="true" />
      <el-table-column label="模型描述" align="left" prop="modelDesc" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['model:base:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['model:base:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模型基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模型名称" />
        </el-form-item>
        <el-form-item label="模型描述" prop="modelDesc">
          <el-input v-model="form.modelDesc" placeholder="请输入模型描述" />
        </el-form-item>
        <el-divider content-position="center">模型详细信息维护</el-divider>

      <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddModelColumnInfo">添加</el-button>
          </el-col>
      </el-row>

      <vxe-table
                border
                row-key
                keep-source
                :edit-rules="validRules"
                :loading="loading"
                ref="xTable1"
                :edit-config="{trigger: 'click', mode: 'cell', showStatus: true}"
                class="sortable-row-demo"
                :menu-config="tableMenu"
                :data="modelColumnInfoList"
                @context-menu-click="contextMenuClickEvent">
              <vxe-table-column width="60">
                <template v-slot>
                  <span class="drag-btn">
                    <i class="vxe-icon--menu"></i>
                  </span>
                </template>
              </vxe-table-column>
              <vxe-table-column field="columnCode" title="列名" :edit-render="{name: 'input', immediate: true, attrs: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="columnName" title="备注" :edit-render="{name: 'input', immediate: true, attrs: {type: 'text'}}" show-overflow></vxe-table-column>               
              <vxe-table-column field="columnType" title="数据类型" :edit-render="{name: 'select', options: dict.type.sys_data_type}"></vxe-table-column>           
            </vxe-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBase, getBase, delBase, addBase, updateBase, exportBase } from "@/api/model/base";
import Sortable from 'sortablejs'

export default {
  name: "Base",
  dicts: ['sys_data_type'],
  data() {
    const roleValid = ({ cellValue }) => {
      const temp = this.modelColumnInfoList.filter(function(item) {
          return cellValue == item.columnCode 
        });
      if (temp.length > 1) {
        return new Error('Code已经存在')
      }
    }
    return {
      tableMenu: {
        className: "menuClass",
        body: {
          options: [
            [
              { code: 'insertAt', name: '插入', disabled: false },
              { code: 'remove',   name: '删除', disabled: false },
            ]
          ]
        },
        visibleMethod: this.visibleMethod
      },
      validRules: {
        columnCode: [
              { required: true, message: 'Code必须填写' },
              { pattern: '^[a-zA-Z][a-zA-Z0-9]*$', message: '格式不正确,由字母和数据组成，首字母不能是数字' },
              { min: 2, max: 30, message: '请输入2-30位', trigger: 'blur'},
              { validator: roleValid }
        ],
        columnName: [
          { required: true, message: "备注不能为空", trigger: "blur" },  
          { min: 2, max: 30, message: '请输入2-30位', trigger: 'blur'}
        ],
        columnType: [
          { required: true, message: "数据类型不能为空", trigger: "blur" }
        ],
      },
      showHelpTip1: true,
      currentColumn:null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedModelColumnInfo: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模型基本信息表格数据
      baseList: [],
      // 模型详细信息表格数据
      modelColumnInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
        modelDesc: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelName: [
          { required: true, message: "模型名称不能为空", trigger: "blur" },
          { min: 2, max: 30, message: '请输入2-30位', trigger: 'blur'},
        ],  
        modelDesc: [
          { min: 2, max: 100, message: '请输入2-100位', trigger: 'blur'},
        ],        
      }
    };
  },
  created() {
    this.getList();    
  },
  methods: {
    /** 查询模型基本信息列表 */
    getList() {
      this.loading = true;
      listBase(this.queryParams).then(response => {
        this.baseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelId: null,
        modelName: null,
        modelDesc: null
      };
      this.modelColumnInfoList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.modelId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模型基本信息";
      this.rowDrop();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const modelId = row.modelId || this.ids
      getBase(modelId).then(response => {
        this.form = response.data;
        this.modelColumnInfoList = response.data.modelColumnInfoList;
        this.open = true;
        this.title = "修改模型基本信息";
        this.rowDrop();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$refs.xTable1.validate(true).then(x => {
             for(var ind = 0; ind < this.modelColumnInfoList.length; ind++) {
                this.modelColumnInfoList[ind].columnOrder = ind ;
              }
              this.form.modelColumnInfoList = this.modelColumnInfoList;
              if (this.form.modelId != null) {
                updateBase(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addBase(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }

          }).catch(x => x);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.$modal.confirm('是否确认删除模型基本信息编号为"' + modelIds + '"的数据项？').then(function() {
        return delBase(modelIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 模型详细信息序号 */
    rowModelColumnInfoIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 模型详细信息添加按钮操作 */
    handleAddModelColumnInfo() {
      let obj = {};
      obj.columnCode = "";
      obj.columnName = "";
      obj.columnType = "4";
      this.modelColumnInfoList.push(obj);
    },
    /** 模型详细信息删除按钮操作 */
    handleDeleteModelColumnInfo() {
      if (this.checkedModelColumnInfo.length == 0) {
        this.$modal.msgError("请先选择要删除的模型详细信息数据");
      } else {
        const modelColumnInfoList = this.modelColumnInfoList;
        const checkedModelColumnInfo = this.checkedModelColumnInfo;
        this.modelColumnInfoList = modelColumnInfoList.filter(function(item) {
          return checkedModelColumnInfo != item.index 
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有模型基本信息数据项？').then(() => {
        this.exportLoading = true;
        return exportBase(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    rowDrop () {
        this.$nextTick(() => {
          let xTable = this.$refs.xTable1          
          this.sortable = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
            handle: '.drag-btn',
            onEnd: ({ newIndex, oldIndex }) => {
              let currRow = this.modelColumnInfoList.splice(oldIndex, 1)[0]
              this.modelColumnInfoList.splice(newIndex, 0, currRow)
            }
          })
        })
      },
    visibleMethod ({ options, column }) {
      let isDisabled = !column
      options.forEach(list => {
        list.forEach(item => {
          item.disabled = isDisabled
        })
      })
      return true
    },
    contextMenuClickEvent ({ menu, row, column }) {
      let xTable = this.$refs.xTable1
      switch (menu.code) {
        case 'hideColumn':
          xTable.hideColumn(column)
          break
        case 'showAllColumn':
          xTable.resetColumn()
          break
        case 'copy':
          if (XEClipboard.copy(row[column.property])) {
            this.$XModal.message({ message: '已复制到剪贴板！', status: 'success' })
          }
          break
        case 'reload':
          this.handleUpdate({modelId:this.form.modelId})
          break
        case 'insertAt':
          this.insertEvent(row, column)
          break
        case 'remove':
          xTable.remove(row)
          this.modelColumnInfoList = xTable.getTableData().tableData ;
          break
        case 'save':
          this.$XModal.message({ message: '保存成功', status: 'success' })
          this.submitForm()
          break
      }
    },
    insertEvent (row, column) {
      let xTable = this.$refs.xTable1
      var obj = {
        columnCode:"",
        columnName:"",
        columnType:"4"
      } ;
      xTable.insertAt(obj, row)
      .then(({ row }) => xTable.setActiveCell(row, column.property))
      this.modelColumnInfoList = xTable.getTableData().tableData ;
      //this.modelColumnInfoList.splice(2, 1);
    },
  }
};
</script>
<style>
  .sortable-row-demo .drag-btn {
    cursor: move;
    font-size: 12px;
  }
  .sortable-row-demo .vxe-body--row.sortable-ghost,
  .sortable-row-demo .vxe-body--row.sortable-chosen {
    background-color: #dfecfb;
  }
  .vxe-input--panel.type--date, .vxe-input--panel.type--month, .vxe-input--panel.type--week, .vxe-input--panel.type--year {
         z-index: 9998 !important
  }
  .vxe-select--panel {
    z-index: 9997 !important
  }

</style>

<style>
  .menuClass {
      z-index: 9999 !important;
    }
</style>